import styles from './sale.module.scss'
/* 引入 查询商品列表和 创建订单的接口*/
import {queryProductList,createOrder} from "@/apis"
import {useEffect, useState} from "react";
import type { RadioChangeEvent } from 'antd';
import { Radio } from 'antd';
import {SaleProduct, SaleProductEnum} from "@/types/sale_product";
import {useAccessStore} from "@/app/store/access";
import {effect} from "zod";
import QRCode from "qrcode.react";
import {useNavigate} from "react-router-dom";
import { toast } from 'react-toastify';  
import 'react-toastify/dist/ReactToastify.css'; // 引入样式  

export  function Sale(){
    // 封装接口调用返回来的商品列表
    const [product,setProduct] = useState<SaleProduct[]>([])
    // 下单返回的支付URL
    const [payUrl, setPayUrl] = useState('')
    // 下单成功后 唤起支付二维码
    const [showModal, setShowModal] = useState(false);
    // 编程式路由跳转
    const navigate = useNavigate();
    // 支付类型
    const [payType, setPayType] = useState(0);
    const onChange = (e: RadioChangeEvent) => {
        console.log('radio checked', e.target.value);
        setPayType(e.target.value);
    };
    // 下单
    const payOrder = async  (productId : number) => {
        console.log("产品productId: ",productId)
        console.log("支付类型payType: ",payType)
        // 下单的时候将支付类型传递过去
        const res = await createOrder(productId,payType)
        const {data,code} = await res.json()
        // 登录拦截
        if (code === SaleProductEnum.NeedLogin) {
            useAccessStore.getState().goToLogin();
        }
        // 支付唤起
        if (code == SaleProductEnum.SUCCESS) {
            setPayUrl(data);
            handleButtonClick();
        }
    }
    const handleButtonClick = () => {
        setShowModal(true);
    };

    const handleCloseModal = () => {
        setShowModal(false);
        alert('您还获得了抽奖机会，快去试试运气吧!');
        // toast.success('恭喜您获得2次抽奖机会！', {  
        //     position: "top-right",  
        //     autoClose: 5000, // 自动关闭时间，单位是毫秒  
        //     hideProgressBar: false,  
        //     closeOnClick: true,  
        //     pauseOnHover: true,  
        //     draggable: true,  
        //     progress: undefined,  
        // });  
    };
    // 页面挂在完成后调用 查询商品列表接口
    const queryProductListHandler = async () => {
        const res = await queryProductList()
        const {data,code} = await res.json()
        // 登录拦截
        if (code === SaleProductEnum.NeedLogin) {
            useAccessStore.getState().goToLogin();
        }
        setProduct(data)
    }



    useEffect(() => {
        console.log("页面挂载完成")
        queryProductListHandler().then(res => {
            console.log(res)
        })
    }, [])



    return (
        <div className={styles["sale"]}>
            {
                product?.map((product) => (
                    <div key={product.productId} className={styles["product"]}>
                        <div className={styles["product-name"]}>
                            {product.productName}
                        </div>
                        <div className={styles["product-token"]}>
                            {product.quota}<span className={styles["product-token-subscript"]}>(条)</span>
                        </div>
                        <div className={styles["product-price"]}>
                            <span style={{color: '#af0000', fontSize: "20px"}}>￥{product.price.toFixed(2)}</span>
                        </div>
                        <div className={styles["pay-type"]}>
                            <Radio.Group onChange={onChange} value={payType}>
                                <Radio value={0}>微信支付</Radio>
                                <Radio value={1}>支付宝支付</Radio>
                                <Radio value={2}>银联</Radio>
                            </Radio.Group>
                        </div>
                        <div className={styles["product-buy"]} onClick={() => payOrder(product.productId)}>
                            立即购买
                        </div>
                        <div className={styles["product-desc"]}>
                            <span>{product.productDesc}</span>
                        </div>
                    </div>
                ))
            }
            {showModal && (
                <div className={styles["product-pay"]}>
                    <div className={styles["product-pay-weixin"]}>
                        微信扫码支付
                        <br></br>【模拟支付，权益已发放】
                    </div>
                    <div className={styles["product-pay-url"]}>
                        <QRCode value={payUrl}/>
                    </div>
                    <div className={styles["product-pay-close"]}>
                        <div onClick={handleCloseModal}>我已完成支付</div>
                    </div>
                    <div className={styles["product-pay-prompt"]}>
                        <span>支付成功，自动充值。可直接去<span style={{color: "rgb(0,0,0)", fontWeight: "bold"}}
                                                              onClick={() => {
                                                                  navigate(`/chat`);
                                                              }}>【对话】</span>使用</span>
                    </div>
                </div>
            )}

        </div>
    )
}
